<script setup>
import { ref, watch, onMounted } from 'vue';
import { queryPageEmpApi, saveEmpApi,queryEmpByIdApi,updateApi,deleteByidsApi } from "@/api/emp.js";
import { queryAllApi as queryAllDeptApi } from "@/api/dept.js";
import { ElMessage,ElMessageBox } from 'element-plus';
//定义基础数据
//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 }, { name: '讲师', value: 2 }, { name: '学工主管', value: 3 }, { name: '教研主管', value: 4 }, { name: '咨询师', value: 5 }, { name: '其他', value: 6 }])
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }]);
//部门列表数据
const depts = ref([]);

//查询所有部门
const queryAllDept = async () => {
  const result = await queryAllDeptApi();
  if (result.code) {
    depts.value = result.data;
  }
};


const searchEmp = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
});



//监听searchEmp.date的变化
watch(() => searchEmp.value.date, (newValue, oldValue) => {
  if (searchEmp.value.date && newValue.length > 0) {
    searchEmp.value.begin = newValue[0];
    searchEmp.value.end = newValue[1];
  } else {
    searchEmp.value.begin = '';
    searchEmp.value.end = '';
  }

})

//查询方法
const search = async () => {
  const result = await queryPageEmpApi(searchEmp.value.name, searchEmp.value.gender,
    searchEmp.value.begin, searchEmp.value.end, currentPage.value, pageSize.value)
  if (result.code) {
    empList.value = result.data.rows;
    total.value = result.data.total;
  }
}

//清空方法
const clean = () => {
  searchEmp.value = { name: '', gender: '', date: [], begin: '', end: '' };
  search();
}

const empList = ref([]);

//当前页码
const currentPage = ref(1);
//每页显示条数
const pageSize = ref(10);
//total
const total = ref(0);
//页面大小变化执行
const handleSizeChange = (val) => {
  search();
}
//页码变化执行
const handleCurrentChange = (val) => {
  search();
}

//钩子函数
onMounted(() => {
  search();
  queryAllDept();
  getToken();
})

//新增/修改表单
const employeeFormRef = ref(null)
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')

//文件上传
const imageUrl = ref('')
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  employee.value.image = response.data;
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

//弹出新增员工对话框
const add = () => {

  //清空校验规则
  //重置表单校验信息 resetFields()
  if(employeeFormRef.value){
    employeeFormRef.value.resetFields();
  }
  dialogVisible.value = true;
  dialogTitle.value = '新增员工';
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }
}

//添加工作经历
const addExpr = () => {
  employee.value.exprList.push({
    company: '',
    job: '',
    begin: '',
    end: '',
    exprDate: []
  })
}
//删除工作经历
const deleteExpr = (index) => {
  employee.value.exprList.splice(index, 1)
}

//侦听员工经历的时期数组
watch(()=>employee.value.exprList, (newValue, oldValue) => {
  console.log("侦听员工经历的时期数组");
  if (employee.value.exprList && employee.value.exprList.length > 0) {
    employee.value.exprList.forEach(expr => {
      expr.begin = expr.exprDate[0];
      expr.end = expr.exprDate[1];
    })
  } else {
    employee.value.exprList.forEach(expr => {
      expr.begin = '';
      expr.end = '';
    }) 
  }
},{deep:true})

//新增员工
const save = async () => {
  //数据校验
  if (!employeeFormRef) return
  await employeeFormRef.value.validate(async (valid, fields) => {
    if (valid) {

      let result;
      if(employee.value.id){
         result = await updateApi(employee.value);
      }else{
         result = await saveEmpApi(employee.value);
      }

    if (result.code) {
      dialogVisible.value = false;
      search();
      ElMessage.success(result.message)
    } else {
      ElMessage.error(result.message)
    }
    }else{
      ElMessage.error('请输入有效信息')
    
    }
   
  }
  )
}

//表单校验规则
const rules = ref({
  username: [
    { required: true, message: '用户名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名必须得在2-10位之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名必须得在2-10位之间', trigger: 'blur' }
  ],
  gneder: [
    { required: true, message: '姓名为必填项', trigger: 'change' },
  ],

  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' } //正则表达式 : ^ 开头，$ 结尾, \d 匹配数字
  ]
})

//查询回显
const edit = async(id)=>{
const result = await queryEmpByIdApi(id);

if(result.code){
  dialogVisible.value = true;
  dialogTitle.value = '修改员工';
  employee.value = result.data;

  employee.value.exprList.forEach(expr => {
    expr.exprDate = [expr.begin,expr.end]
  });
}
}

//根据id删除员工
const deleteDept = (id)=>{
  ElMessageBox.confirm(
    '您确定要删除员工吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const result = await deleteByidsApi(id);
      search();
      if(result.code){
        ElMessage.success(result.message);
      }else{
        ElMessage.error(result.message);
      }
    })
    .catch((err) => {
      console.log(err)
     ElMessage.info("操作取消")
    })
}

const ids = ref([]);
//复选框改变触发方法
const handleSelectionChange = (valArr)=>{
  ids.value = [];
  valArr.forEach(e => {
    ids.value.push(e.id);
  });
}

const deleteIds = ()=>{
  ElMessageBox.confirm(
    '您确定要删除员工吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const result = await deleteByidsApi(ids.value);
      search();
      if(result.code){
        ElMessage.success(result.message);
      }else{
        ElMessage.error(result.message);
      }
    })
    .catch((err) => {
      console.log(err)
     ElMessage.info("操作取消")
    })
}
//获取token
const token = ref('');
const getToken = ()=>{
 const loginUser =  localStorage.getItem('loginUser');
 if(loginUser){
  token.value = JSON.parse(loginUser).token;
 }
}
</script>
<template>
  <h1>员工管理</h1>

  <!--搜索栏-->
  <div class="heard">
    <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchEmp.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="请选择">
        <el-select v-model="searchEmp.gender" placeholder="请选择性别" clearable>
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="入职日期">
        <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="到" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clean">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!--两个按钮-->
  <div class="tool">
    <el-button type="primary" plain @click="add">+新增员工</el-button>
    <el-button type="danger" plain @click="deleteIds">-删除员工</el-button>
  </div>

  <!--表格-->
  <el-table :data="empList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50px" align="center" />
    <el-table-column prop="name" label="姓名" width="100px" align="center" />
    <el-table-column prop="gender" label="性别" width="100px" align="center">
      <template #default="scope">
        {{ scope.row.gender == 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="image" label="头像" width="100px" align="center">
      <template #default="scope">
        <img :src="scope.row.image" alt="头像" width="50px">
      </template>

    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" width="100px" align="center">
      <template #default="scope">
        <span v-if="scope.row.deptName == null">其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="job" label="职位" width="100px" align="center">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else-if="scope.row.job == 5">咨询师</span>
        <span v-else>其他</span>
      </template>

    </el-table-column>
    <el-table-column prop="entryDate" label="入职日期" width="150px" align="center" />
    <el-table-column prop="updateTime" label="最后操作时间" width="200px" align="center">

    </el-table-column>
    <el-table-column prop="" label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" round @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" round @click="deleteDept(scope.row.id)">删除</el-button>
      </template>

    </el-table-column>
  </el-table>

  <!--分页条-->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40, 50]"
    :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />

  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="employeeFormRef" :model="employee" label-width="80px" :rules="rules">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <!-- {{ employee }} -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value"></el-option>

            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
              <el-option v-for="job in jobs" :label="job.name" :value="job.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
              <el-option v-for="dept in depts" :label="dept.name" :value="dept.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
            :headers="{'token':token}"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="employee.image" :src="employee.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addExpr">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row :gutter="3" v-for="(expr, index) in employee.exprList">
        <el-col :span="10">
          <el-form-item  size="small" label="时间" label-width="80px">
            <el-date-picker v-model="expr.exprDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item  size="small" label="公司" label-width="60px">
            <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item  size="small" label="职位" label-width="60px">
            <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteExpr(index)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>


</template>

<style scoped>
.tool {
  margin-bottom: 20px;
}

.heard {
  margin: 10px 0px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>